﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraReports.UI;
using System.IO;
using Ahi.Controller;
using Ahi.Entity;
using Ahi.Config;
using Ahi.Base;
using MongoDB.Driver.Builders;
using DevExpress.XtraReports.Design;
using System.Collections;

namespace Ahi.Raporlama
{
    public partial class RaporGoruntuleyiciForm : Base.BaseForm
    {
        private XtraReport report = new XtraReport();
        public object DataSource { get; set; }

        public RaporGoruntuleyiciForm()
        {
            InitializeComponent();
        }

        public override void Yukle()
        {
            if (Id.HasValue)
            {
                RaporEntity entity = MongoAdaptor.Instance.GetDataById<RaporEntity>(Id.AsObjectId);

                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(entity.KaynakKod)))
                {
                    report.LoadLayout(ms);
                }
                printControl1.PrintingSystem = report.PrintingSystem;

                if (DataSource == null)
                {
                    var tumListe = MongoAdaptor.DB
                        .GetCollection(Utilities.MongoUtil.GetDBCollectionName(entity.DataSourceType))
                        .FindAll().ToList();

                    report.DataSource = tumListe;
                    report.CreateDocument();
                }
                else
                {
                    if (this.DataSource is ICollection)
                        report.DataSource = this.DataSource;
                    else
                    {
                        var lst = new List<object>();
                        lst.Add(this.DataSource);
                        report.DataSource = lst;
                    }
                    report.CreateDocument();
                }
            }
            else
            {
                MessageBox.Show("Rapora ulaşılamadı.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Close();
            }
        }
    }
}
